import React, { useState, useEffect } from 'react';
import { TjContent, TjFilter, TjHeader, TjModal, TjModalTitle, TjOperateLog } from '@/tjComponents';
import { useRequestPowerAfterInit } from '@/hooks/useRequestPowerAfterInit';
import { Button, DatePicker, Drawer, message, Select, Spin } from 'antd';
import TjMarketingUnit from '@/tjComponents/TjMarketingUnit';
import TjTable from '@/pages/ETrade/components/TjTable';
import Charts from './components/Charts';
import AddModal from './components/AddModal';
import moment from 'moment';
import { useSetState } from 'ahooks';
import { addOnlinePower, logUrl, queryAggregateData } from './service';
import { HttpCode } from '#/utils/contacts.js';
import { useForm } from 'antd/es/form/Form';
import { buildChartsData, buildTable } from './helper';
import TRDefault from '@/tool/components/TRTheme/TRDefault';
import { connect } from 'umi';
// @ts-ignore
import { useExcel } from '@/hooks';

import _ from 'lodash';
import type { Moment } from 'moment';
import type { ArtColumn } from 'ali-react-table';
import type { ProvinceType, StationType } from '@/hooks/useRequestPowerAfterInit';

import './index.less';
import LogContent from './components/LogContent';

const { RangePicker } = DatePicker;

const initFilterValue = {
  time: [moment().startOf('month'), moment()],
};
const OnlinePowerAnalysis: React.FC<IOnlinePowerAnalysisProps> = (props) => {
  const [form] = useForm();
  const [currentProvinceInfo, setCurrentProvinceInfo] = useState<ProvinceType>();
  const [defaultValues, setDefaultValues] = useState<any>();
  const { initLoading, province, errorMsg, treeData } = useRequestPowerAfterInit(
    `/power/dataPower/common/${props.menuCode}/t_station`,
    (parmas) => {
      const obj = {
        stationIds: parmas.stations.map((v: StationType) => {
          return v.stationId;
        }),
        marketId: parmas.value,
        ...initFilterValue,
      };
      setCurrentProvinceInfo(parmas);
      setDefaultValues(obj);
      setReq(obj);
    },
    {
      convertResult: '2',
      matchFirst: 0,
    },
  );
  const [loading, setLoading] = useState<boolean>(false);
  const [xAxisData, setXAxisData] = useState<string[]>([]);
  const [chartsDataObj, setChartsDataObj] = useState<any>();
  const [req, setReq] = useSetState<any>({});
  const [columns, setColumns] = useState<ArtColumn[]>([]);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [dates, setDates] = useState<[Moment | null, Moment | null]>([null, null]);
  const [logListVisible, setLogListVisible] = useState<boolean>(false);
  const [logParams, setLogParams] = useState<any>({ date: initFilterValue.time[1] });

  const query = () => {
    const newReq = {
      ...req,
    };
    if (req.time) {
      newReq.startDate = moment(req.time[0]).format('YYYY-MM-DD');
      newReq.endDate = moment(req.time[1]).format('YYYY-MM-DD');
      delete newReq.time;
    }
    delete newReq.refreshTime;
    setLoading(true);
    queryAggregateData(newReq)
      .then((res: any) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          if (res.data.head && res.data.sumBody) {
            const { columns, dataSource } = buildTable(
              res.data.sumBody,
              res.data.head,
              res.data.dataList,
            );
            const { xAxisData, chartsData } = buildChartsData(res.data.head, res.data.dataList);
            setChartsDataObj(chartsData);
            setXAxisData(xAxisData);
            setColumns(columns);
            setDataSource(dataSource);
          }
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const onSearch = (values: any) => {
    setReq(values);
  };

  const onReset = (values: any) => {
    setReq(values);
  };

  const add = () => {
    TjModal.open({
      title: <TjModalTitle title="新增" />,
      content: <AddModal currentStations={currentProvinceInfo?.stations} currentReq={req} />,
      width: 1100,
      destroyOnClose: true,
      maskClosable: false,
      onOk: (values) => {
        return new Promise((resolve, reject) => {
          addOnlinePower(values).then((res: any) => {
            if (res.statusCode === HttpCode.SUCCESS) {
              message.success('新增成功');
              setReq({
                refreshTime: moment().valueOf(),
              });
              resolve('');
            } else {
              message.error(res.message);
              reject();
            }
          });
        });
      },
    });
  };

  const log = () => {
    setLogListVisible(true);
  };

  const onExport = () => {
    if (dataSource.length > 0) {
      const buildExpotrData = dataSource.map((v) => {
        return {
          ...v,
          eorror: v.eorror ? '是,原因：设备问题' : '否',
        };
      });

      useExcel({
        columns: columns,
        data: buildExpotrData,
        filename: `新疆分时段上网电量统计`,
      });
    }
  };

  const changeMarketId = (val: string) => {
    const item = _.find(province, (n: ProvinceType) => n.value === val);
    if (item) {
      setCurrentProvinceInfo(item);
      form.setFieldsValue({
        stationIds: item.stations.map((v: StationType) => {
          return v.stationId;
        }),
      });
    }
  };

  const disabledDate = (current: Moment) => {
    if (!dates || (!dates[0] && !dates[1])) {
      return false;
    }
    const tooLate = dates[0] && current.diff(dates[0], 'months') !== 0;
    const tooEarly = dates[1] && dates[1].diff(current, 'months') !== 0;
    return !!tooEarly || !!tooLate;
  };

  useEffect(() => {
    if (req.marketId && req.stationIds) {
      query();
    }
  }, [req]);

  return (
    <div className="online-power-analysis">
      <TjHeader
        left={
          <TjFilter
            defaultValues={defaultValues}
            form={form}
            items={[
              {
                name: 'marketId',
                render: (
                  <Select
                    options={province}
                    style={{ width: 180 }}
                    loading={initLoading}
                    onChange={changeMarketId}
                  />
                ),
              },
              {
                name: 'stationIds',
                render: (
                  <TjMarketingUnit treeData={treeData} marketId={currentProvinceInfo?.value} />
                ),
              },
              {
                name: 'time',
                render: (
                  <RangePicker
                    onCalendarChange={(val) => setDates(val as any)}
                    disabledDate={disabledDate}
                  />
                ),
              },
            ]}
            onSearch={onSearch}
            onReset={onReset}
            loading={loading || initLoading}
          />
        }
        right={
          <>
            <Button type="link" loading={loading || initLoading} onClick={add}>
              新增
            </Button>
            <Button type="link" loading={loading || initLoading} onClick={onExport}>
              导出
            </Button>
            <Button type="link" loading={loading || initLoading} onClick={log}>
              日志记录
            </Button>
          </>
        }
      />

      <TjContent>
        <Spin spinning={loading}>
          {dataSource.length <= 0 ? (
            <TRDefault type="empty" />
          ) : (
            <div className="content">
              <div className="charts-box">
                <Charts xAxisData={xAxisData} chartsDataObj={chartsDataObj} />
              </div>
              <div className="table-box">
                <TjTable columns={columns} dataSource={dataSource} />
              </div>
            </div>
          )}
        </Spin>
      </TjContent>

      <Drawer
        title={'操作日志'}
        visible={logListVisible}
        width={700}
        onClose={() => setLogListVisible(false)}
        destroyOnClose
      >
        {logListVisible && (
          <TjOperateLog
            queryUrl={logUrl}
            params={{ date: logParams.date.format('YYYY-MM-DD') }}
            header={
              <DatePicker
                style={{ width: 180 }}
                value={logParams.date}
                onChange={(val) => setLogParams({ date: val })}
              />
            }
            content={(item) => {
              return <LogContent data={item} />;
            }}
          />
        )}
      </Drawer>
    </div>
  );
};

interface IOnlinePowerAnalysisProps {
  menuCode: string;
}

export default connect(({ global }: any) => ({
  menuCode: global.configure.menuCode,
}))(OnlinePowerAnalysis);
